package org.azdroid.kit.util;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * @author Steven.Li
 *
 */

/**
 * @author Steven.Li
 */
public final class StringHelper {

	public final static String STR_SEPARATOR = ",";
	public final static String STR_LINE_BREAK = "\n";

	public static final String merger(String s1, String s2, String defaultS2) {
		StringBuffer mSm = new StringBuffer();
		mSm.append(s1);
		mSm.append(": ");
		if (StringHelper.isText(s2)) {
			mSm.append(s2);
		} else {
			mSm.append(defaultS2);
		}
		return mSm.toString();
	}

	/**
	 * 筛除非法字符
	 * 
	 * @param text
	 * @return
	 */
	final public static boolean isText(String text) {
		if (text == null || text.trim().length() == 0 || text.equals("")
				|| text.equals("null") || text.equals("NULL")) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 判断用户是否输入
	 * 
	 * @param context
	 * @param text
	 * @return
	 */
	final public static String checkText(String text) {
		if (isText(text)) {
			return text;
		}
		return "";
	}

	/**
	 * 字符串是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	final public static String getResultTextFromArrays(String[] arrys,
			String allStrIndex) {
		StringBuffer sb = new StringBuffer();
		String str = "";
		if (isText(allStrIndex)) {
			String[] strs = allStrIndex.split(STR_SEPARATOR);
			for (String s : strs) {
				if (isNumeric(s)) {
					int index = Integer.parseInt(s);
					str = arrys[index];
				} else {
					if (isText(s) && s.startsWith(arrys.length - 1 + "")) {
						int startIndex = s.lastIndexOf("@");
						str = s.substring(startIndex + 1);
					}
				}
				if (isText(str)) {
					sb.append(str).append("、");
				}
			}
			str = removeLastSeparator(sb.toString(), "、");
		}
		return str;
	}

	/**
	 * 去除最后的连接符号
	 * 
	 * @param source
	 * @param separator
	 * @return
	 */
	final public static String removeLastSeparator(String source,
			String separator) {
		if (isText(source)) {
			if (source.endsWith(separator)) {
				source = source.substring(0, source.length() - 1);
			}
		}
		return source;
	}

	/**
	 * 去除特殊字符或将所有中文标号替换为英文标号
	 * 
	 * @param str
	 * @return
	 */
	final public static String stringFilter(String str) {
		str = str.replaceAll("【", "[").replaceAll("】", "]")
				.replaceAll("！", "!").replaceAll("：", ":").replaceAll("（", "(")
				.replaceAll("）", ")").replaceAll("“", "\"")
				.replaceAll("”", "\"");// 替换中文标号
		String regEx = "[『』]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	// 半角转化为全角的方法
	final public static String ToSBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127 && c[i] > 32)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	// 全角转化为半角的方法
	final public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (isChinese(c[i])) {
				if (c[i] == 12288) {
					c[i] = (char) 32;
					continue;
				}
				if (c[i] > 65280 && c[i] < 65375)
					c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 判断是否为中文
	 * 
	 * @param c
	 * @return
	 */
	final private static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否是手机号码
	 * 
	 * @param text
	 * @return
	 */
	final public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

		Matcher m = p.matcher(mobiles);

		System.out.println(m.matches() + "---");

		return m.matches();
	}

	/**
	 * bytes[]转换成Hex字符�?可用于URL转换，IP地址转换.
	 */
	final public static String bytesToHexString(byte[] bytes) {
		// http://stackoverflow.com/questions/332079
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	final public static String stringToStringSHA_1(String str) {
		String cacheKey = str;
		MessageDigest mDigest;
		try {
			mDigest = MessageDigest.getInstance("SHA-1");
			mDigest.update(str.getBytes());
			cacheKey = StringHelper.bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return cacheKey;
	}

	final public static String prettyBytes(long value) {

		String args[] = { "B", "KB", "MB", "GB", "TB" };
		StringBuilder sb = new StringBuilder();
		int i;
		if (value < 1024L) {
			sb.append(String.valueOf(value));
			i = 0;
		} else if (value < 1048576L) {
			sb.append(String.format("%.1f", value / 1024.0));
			i = 1;
		} else if (value < 1073741824L) {
			sb.append(String.format("%.2f", value / 1048576.0));
			i = 2;
		} else if (value < 1099511627776L) {
			sb.append(String.format("%.3f", value / 1073741824.0));
			i = 3;
		} else {
			sb.append(String.format("%.4f", value / 1099511627776.0));
			i = 4;
		}
		sb.append(' ');
		sb.append(args[i]);
		return sb.toString();
	}

	/**
	 * 将Excepiton信息转换成String字符�?
	 */
	final public static String exceptionToString(Throwable t) {
		if (t == null)
			return null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			t.printStackTrace(new PrintStream(baos));
		} finally {
			try {
				baos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return baos.toString();
	}

	final public static String getPriceSpread(String price1, String price2) {

		try {
			Float saveMoney = Float.valueOf(price1) - Float.valueOf(price2);
			saveMoney = Math.abs(saveMoney);
			return new DecimalFormat("###0.00").format(saveMoney);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return "0.00";
		}
	}

	final public static String formatDouble(double d) {
		return new DecimalFormat("###0.00").format(d);
	}

	final public static int string2Int(String string) {
		int result = 0;
		try {
			result = Integer.valueOf(string);
		} catch (NumberFormatException e) {
			result = -1;
			e.printStackTrace();
		}
		return result;
	}

	final public static String int2String(int value) {
		String result = null;
		try {
			result = String.valueOf(value);
		} catch (Exception e) {
			result = null;
			e.printStackTrace();
		}

		return result;
	}

	final public static boolean idDouble(String value) {
		boolean flag = false;
		try {
			Double.parseDouble(value);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}

		return flag;
	}

	final public static StringBuilder removeLastSeparator(StringBuilder source,
			String separator) {
		int pos = source.lastIndexOf(separator);
		if (pos != -1)
			return source.delete(pos, source.length());
		return source;
	}

	/**
	 * 按args匹配是不是32位数据库中的uuid值
	 */
	public static boolean isUUID(String args) {
		if (!isText(args)) {
			return false;
		}
		String reg = "[0-9a-z]{32}";
		boolean flag = args.matches(reg);
		return flag;
	}

	final public static int generateAge(String birthday) {
		if (!isText(birthday))
			return 0;
		Date birthdate;
		int age = 0;
		try {
			birthdate = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
			Calendar currentDay = Calendar.getInstance();
			currentDay.setTime(birthdate);
			int year = currentDay.get(Calendar.YEAR);
			// 获取年龄
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
			String years = simpleDateFormat.format(new Date());
			age = Integer.parseInt(years) - year;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return age;
	}

	public static String fromArrayAsString(String[] array, String strIndex) {
		String content = "";
		if (isText(strIndex) && isNumeric(strIndex)) {
			int index = Integer.parseInt(strIndex);
			if (array != null && array.length > 0 && index < array.length) {
				content = array[index];
				return content;
			}
		}
		return content;
	}

	/**
	 * 获取系统版本号
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getVersionName(Context context) throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(
				context.getPackageName(), 0);
		String version = packInfo.versionName;
		return version;
	}
}
